package com.stars.easyms.datasource.jdbc;

import com.stars.easyms.datasource.EasyMsMultiDataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
import org.springframework.lang.Nullable;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>className: EasyMsSQLErrorCodeSQLExceptionTranslator</p>
 * <p>description: EasyMs自定义SQLErrorCodeSQLExceptionTranslator类</p>
 *
 * @author guoguifang
 * @date 2019-11-22 20:21
 * @since 1.4.1
 */
public final class EasyMsSQLErrorCodeSQLExceptionTranslator extends SQLErrorCodeSQLExceptionTranslator {

    private static final Map<DataSource, SQLErrorCodeSQLExceptionTranslator> TRANSLATOR_MAP = new ConcurrentHashMap<>();

    private EasyMsMultiDataSource easyMsMultiDataSource;

    public EasyMsSQLErrorCodeSQLExceptionTranslator(DataSource dataSource) {
        if (dataSource instanceof EasyMsMultiDataSource) {
            this.easyMsMultiDataSource = (EasyMsMultiDataSource) dataSource;
        } else {
            setDataSource(dataSource);
        }
    }

    EasyMsSQLErrorCodeSQLExceptionTranslator(EasyMsMultiDataSource easyMsMultiDataSource) {
        this.easyMsMultiDataSource = easyMsMultiDataSource;
    }

    @Override
    public DataAccessException translate(String task, @Nullable String sql, SQLException ex) {
        if (easyMsMultiDataSource == null) {
            return super.translate(task, sql, ex);
        }
        return TRANSLATOR_MAP.computeIfAbsent(easyMsMultiDataSource.getCurrentDataSource(), SQLErrorCodeSQLExceptionTranslator::new).translate(task, sql, ex);
    }

}